package com.itheima.pinda.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.pinda.DTO.truck.TruckLicenseDto;
import com.itheima.pinda.common.CustomIdGenerator;
import com.itheima.pinda.entity.PdTruck;
import com.itheima.pinda.entity.PdTruckLicense;
import com.itheima.pinda.mapper.PdTruckLicenseMapper;
import com.itheima.pinda.mapper.PdTruckMapper;
import com.itheima.pinda.service.PdTruckLicenseService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service
public class PdTruckLicenseServiceImpl implements PdTruckLicenseService {

    @Autowired
    private CustomIdGenerator idGenerator;
    @Autowired
    private PdTruckLicenseMapper truckLicenseMapper;
    @Autowired
    private PdTruckMapper truckMapper;

    @Override
    @Transactional
    public TruckLicenseDto licenseInsertAndUpdate(TruckLicenseDto truckLicenseDto) {
        PdTruckLicense truckLicense = new PdTruckLicense();
        BeanUtils.copyProperties(truckLicenseDto,truckLicense);
        if (StringUtils.isEmpty(truckLicense.getId())) {
            // 新增
            truckLicense.setId(idGenerator.nextId(truckLicense) + "");
            truckLicenseMapper.insert(truckLicense);
            // 更新车辆信息
            truckMapper.update(null,
                    new LambdaUpdateWrapper<PdTruck>()
                            .set(PdTruck::getTruckLicenseId, truckLicense.getId())
                            .eq(PdTruck::getId, truckLicense.getTruckId()));
            truckLicenseDto.setId(truckLicense.getId());
        }else {
            // 修改
            truckLicenseMapper.updateById(truckLicense);
        }

        return truckLicenseDto;
    }

    @Override
    public TruckLicenseDto selectById(String id) {
        PdTruckLicense pdTruckLicense = truckLicenseMapper.selectById(id);
        TruckLicenseDto truckLicenseDto = new TruckLicenseDto();
        BeanUtils.copyProperties(pdTruckLicense,truckLicenseDto);
        return truckLicenseDto;
    }
}
